package com.kexilo.core.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 多租户配置
 * 支持多租户数据隔离和上下文管理
 * 
 * @author Kexilo
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.features", name = "multitenant-enabled", havingValue = "true", matchIfMissing = false)
public class MultiTenantConfig {
    
    private static final Logger log = LoggerFactory.getLogger(MultiTenantConfig.class);
    
    /**
     * 租户上下文持有者
     */
    public static final class TenantContextHolder {
        private static final ThreadLocal<String> CURRENT_TENANT = new ThreadLocal<>();
        
        public static void setTenantId(String tenantId) {
            CURRENT_TENANT.set(tenantId);
        }
        
        public static String getTenantId() {
            return CURRENT_TENANT.get();
        }
        
        public static void clear() {
            CURRENT_TENANT.remove();
        }
    }
    
    /**
     * 租户过滤器
     * 从请求头中提取租户ID并设置到上下文中
     */
    @Bean
    public OncePerRequestFilter tenantFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, 
                                          HttpServletResponse response, 
                                          FilterChain filterChain) throws ServletException, IOException {
                try {
                    // 从请求头中获取租户ID
                    String tenantId = request.getHeader("X-Tenant-Id");
                    if (tenantId == null || tenantId.trim().isEmpty()) {
                        // 也可以从子域名或路径参数中获取
                        tenantId = extractTenantFromHost(request.getServerName());
                    }
                    
                    if (tenantId != null) {
                        TenantContextHolder.setTenantId(tenantId);
                        log.debug("设置租户上下文: {}", tenantId);
                    }
                    
                    filterChain.doFilter(request, response);
                } finally {
                    // 清理租户上下文
                    TenantContextHolder.clear();
                }
            }
            
            private String extractTenantFromHost(String host) {
                // 从子域名提取租户ID，例如: tenant1.kexilo.com -> tenant1
                if (host != null && host.contains(".")) {
                    String[] parts = host.split("\\.");
                    if (parts.length > 2) {
                        return parts[0];
                    }
                }
                return null;
            }
        };
    }
    
    /**
     * 多租户MyBatis拦截器
     * 自动为SQL添加租户条件
     */
    // TODO: 实现MyBatis拦截器，自动为查询添加tenant_id条件
    
    /**
     * 多租户缓存键前缀
     */
    public static String getTenantCacheKey(String originalKey) {
        String tenantId = TenantContextHolder.getTenantId();
        if (tenantId != null) {
            return "tenant:" + tenantId + ":" + originalKey;
        }
        return originalKey;
    }
}

